package com.app.car.check;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.Switch;
import android.widget.TextView;

import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.app.car.R;
import com.app.car.basis.BasisApp;
import com.app.car.basis.Constants;
import com.app.car.bean.RfidListBean;
import com.app.car.bean.RfidListData;
import com.app.car.greendao.GreenDaoUtils;
import com.app.car.home.HomeBaseActivity;
import com.app.car.util.ExcelUtil;
import com.app.car.util.MyUtils;
import com.leon.lfilepickerlibrary.LFilePicker;
import com.leon.lfilepickerlibrary.utils.Constant;
import com.realopeniot.uar_utils.R2000Utils;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import io.reactivex.rxjava3.android.schedulers.AndroidSchedulers;
import io.reactivex.rxjava3.core.Observable;
import io.reactivex.rxjava3.core.ObservableEmitter;
import io.reactivex.rxjava3.core.ObservableOnSubscribe;
import io.reactivex.rxjava3.core.Observer;
import io.reactivex.rxjava3.disposables.Disposable;
import io.reactivex.rxjava3.schedulers.Schedulers;
import my.DialogUtils;
import my.LogUtil;

/**
 * 盘点界面
 */
public class CheckIndexActivity extends HomeBaseActivity implements CheckView{

    CheckPresent present;

    @BindView(R.id.switch_auto)
    Switch switch_auto;
    @BindView(R.id.icon_line_one)
    ImageView icon_line_one;   // 天线一
    @BindView(R.id.icon_line_two)
    ImageView icon_line_two;   // 天线二
    @BindView(R.id.icon_line_three)
    ImageView icon_line_three;   // 天线三
    @BindView(R.id.icon_line_four)
    ImageView icon_line_four;   // 天线四

    @BindView(R.id.text_xls)
    TextView text_xls;   // excel文件名,或者数量
    @BindView(R.id.text_num)
    TextView text_num;   // 已经扫到多少标签码
    @BindView(R.id.img_start)
    ImageView imgStart;      //开始按钮
    @BindView(R.id.img_gif)
    ImageView imgGif;      //开始按钮

    @BindView(R.id.recyclerview)
    RecyclerView rfidRecycle;
    RfidAdapter rfidAdapter;
    RfidListBean rfidListBean;

    private R2000Utils jni_r2000Utils;
    private boolean startFindRfid;

    @Override
    public void initViews() {
        super.initViews();
        setContentView(R.layout.check_index_activity);
        EventBus.getDefault().register(this);

        jni_r2000Utils = new R2000Utils();
        jni_r2000Utils.openR2000();
        present = new CheckPresentImpl(this,this);
    }

    @Override
    public void initData(Bundle savedInstanceState) {
        super.initData(savedInstanceState);
        rfidListBean = new RfidListBean();
        LinearLayoutManager layoutManager = new LinearLayoutManager(mContext);
        layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        rfidRecycle.setLayoutManager(layoutManager);
        rfidAdapter = new RfidAdapter();
        rfidRecycle.setAdapter(rfidAdapter);
        toFindRfid();
    }


    @OnClick({R.id.view_check, R.id.view_start, R.id.view_clear,R.id.view_in,R.id.view_line_one,R.id.view_line_two,R.id.view_line_three})
    public void btnClick(View v) {
        switch (v.getId()) {
            case R.id.view_check:
                if(rfidListBean == null || rfidListBean.getCheckRfidList().size()<1){
                    showToast("请先盘点");
                    return;
                }
                stop();
                present.toCheck(rfidListBean);
                break;
            case R.id.view_start:
                if(startFindRfid){
                    stop();
                }else {
                    wireNumberList =  MyUtils.getAirWire();
                    start();
                }
                break;
            case R.id.view_clear:
                rfidListBean = new RfidListBean();
                originalRfidList = new ArrayList<>();
                setRfidRecycle();
                text_xls.setText("请选择数据源");
                break;
            case R.id.view_in:
                if(startFindRfid){
                    DialogUtils.showErrorDialog(mContext,"请暂停并清空");
                    return;
                }
                new LFilePicker()
                        .withActivity(CheckIndexActivity.this)
                        .withRequestCode(REQUEST_READ_FILE_CHOOSE)
                        .withTitle("文件选择")
                        .withBackgroundColor("#0396FF")
                        .withMutilyMode(false)
                        .withMaxNum(1)
//                                .withStartPath("/storage")//指定初始显示路径
                        .withStartPath(Constants.DIR_EXCEL)//指定初始显示路径
                        .withFileFilter(new String[]{"xls", "xlsx"})
                        .start();
                break;
            case R.id.view_line_one:
                setAntennaParam(1);
                break;
            case R.id.view_line_two:
                setAntennaParam(2);
                break;
            case R.id.view_line_three:
                setAntennaParam(3);
                break;
            case R.id.view_line_four:
                setAntennaParam(4);
                break;


        }
    }

    public void setAntennaParam( int number){

        if(switch_auto.isChecked()){
            showToast("自动模式下无法选择");
            return ;
        }
        if(startFindRfid){
            showToast("请先关闭盘点扫描");
            return ;
        }

        icon_line_one.setImageResource(R.mipmap.icon_wire_white);
        icon_line_two.setImageResource(R.mipmap.icon_wire_white);
        icon_line_three.setImageResource(R.mipmap.icon_wire_white);
        icon_line_four.setImageResource(R.mipmap.icon_wire_white);
        switch (number){
            case 1:
                icon_line_one.setImageResource(R.mipmap.icon_wire_blue);
                break;
            case 2:
                icon_line_two.setImageResource(R.mipmap.icon_wire_blue);
                break;
            case 3:
                icon_line_three.setImageResource(R.mipmap.icon_wire_blue);
                break;
            case 4:
                icon_line_four.setImageResource(R.mipmap.icon_wire_blue);
                break;
        }

        boolean a = false;
        while (!a){
            a =  jni_r2000Utils.setAntennaParam(new R2000Utils.AntennaParam(number));
        }
        showToast("设置成功");
    }


    public class RfidAdapter extends RecyclerView.Adapter<RfidAdapter.ViewHolder> {


        //创建新View，被LayoutManager所调用
        @Override
        public ViewHolder onCreateViewHolder(ViewGroup viewGroup, int viewType) {
            View view = LayoutInflater.from(mContext).inflate(R.layout.check_index_item, viewGroup, false);
            return new ViewHolder(view);
        }


        //将数据与界面进行绑定的操作
        @Override
        public void onBindViewHolder(ViewHolder viewHolder, int position) {
            viewHolder.bind(position);
        }

        //获取数据的数量
        @Override
        public int getItemCount() {
            return rfidListBean == null ? 0 : rfidListBean.getCheckRfidList().size();
        }

        //自定义的ViewHolder，持有每个Item的的所有界面元素
        public class ViewHolder extends RecyclerView.ViewHolder {
            @BindView(R.id.list_item)
            public View list_item;
            @BindView(R.id.text_no)
            public TextView text_no;
            @BindView(R.id.text_ant)
            public TextView text_ant;
            @BindView(R.id.text_rfid)
            public TextView text_rfid;
            @BindView(R.id.text_gid)
            public TextView text_gid;
            @BindView(R.id.text_name)
            public TextView text_name;

            public ViewHolder(View view) {
                super(view);
                ButterKnife.bind(this, view);
            }

            public void bind(int position) {
                RfidListData data = rfidListBean.getCheckRfidList().get(position);
                text_no.setText(""+(position++));
                text_ant.setText(""+data.getAnt());
                text_rfid.setText(data.getRfid());
                text_gid.setText(data.getGid());
                text_name.setText(data.getName());
                list_item.setTag(data);
            }

            @OnClick(R.id.list_item)
            public void onItemClick(View v) {

            }

        }
    }

    private void setRfidRecycle() {
        if (rfidAdapter == null) {
            rfidAdapter = new RfidAdapter();
            rfidRecycle.setAdapter(rfidAdapter);
        } else {
            rfidAdapter.notifyDataSetChanged();
            rfidRecycle.scrollToPosition(rfidAdapter.getItemCount() - 1);
            text_num.setText(""+rfidAdapter.getItemCount());
        }
    }


    private void stop(){
        imgStart.setImageResource(R.mipmap.icon_start);
        startFindRfid = false;
        BasisApp.loadGif(mContext,R.mipmap.gif_num_stop,imgGif);
    }

    private void start(){
        imgStart.setImageResource(R.mipmap.icon_stop);
        startFindRfid = true;
        BasisApp.loadGif(mContext,R.mipmap.gif_num_start,imgGif);
    }

    List<Integer> wireNumberList;
    List<String> originalRfidList;
    int currentWire = 0;
    int haveNewRfidBean = 0;
    private void toFindRfid(){
        wireNumberList =  MyUtils.getAirWire();
        originalRfidList = new ArrayList<>();
        currentWire = jni_r2000Utils.getAntennaParam().getAntennaNumber()-1;
//        setAntennaParam(currentWire,false);

        rfidListBean.setTime(System.currentTimeMillis());
        Observable.create(new ObservableOnSubscribe<Integer>() {
            // 1. 创建被观察者 & 生产事件
            @Override
            public void subscribe(ObservableEmitter<Integer> emitter) throws Exception {
                while (!mContext.isFinishing()){
                    if (startFindRfid){
//                        LogUtil.d("??position ==" +position);
                        ArrayList<R2000Utils.Epc1g2InventoryParam> tag = jni_r2000Utils.epc1g2RealTimeInventory();
//                        LogUtil.d("??tag。size ==" +tag.size());
                        for (R2000Utils.Epc1g2InventoryParam data : tag){
                            originalRfidListAdd(data.getEpc(),data.getAnt());
                        }

                        if(haveNewRfidBean != 0){
                            haveNewRfidBean = 0;
                            emitter.onNext(99);
                        }
//                        if(switch_auto.isChecked()){
                            if(currentWire >= wireNumberList.size()){
                                currentWire = 0;
                            }

                            boolean a = false;
                            while (!a){
                                a =  jni_r2000Utils.setAntennaParam(new R2000Utils.AntennaParam(wireNumberList.get(currentWire)));
                            }
                            currentWire++;
//                        }
                    }
                }
                emitter.onComplete();
            }
        })
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<Integer>() {
                    // 2. 通过通过订阅（subscribe）连接观察者和被观察者
                    // 3. 创建观察者 & 定义响应事件的行为
                    @Override
                    public void onSubscribe(Disposable d) {

                        LogUtil.d("开始采用subscribe连接");
                    }
                    // 默认最先调用复写的 onSubscribe（）

                    @Override
                    public void onNext(Integer value) {
//                LogUtil.d("对Next事件"+ value +"作出响应");
                        LogUtil.d("???="+"对Next事件"+ value +"作出响应");
                        switch (value){
                            case 99:
                                setRfidRecycle();
                                break;
                        }
                    }

                    @Override
                    public void onError(Throwable e) {
                        LogUtil.d("对Error事件作出响应");
                    }

                    @Override
                    public void onComplete() {

                        LogUtil.d("对Complete事件作出响应");
                    }

                });
    }


    private void originalRfidListAdd(String rfid,int ant){
        if(originalRfidList == null) originalRfidList = new ArrayList<>();
        if(!originalRfidList.contains(rfid)){
            originalRfidList.add(rfid);
            rfidListBean.addData(rfid,ant);
//            rfidListBean.addData(GreenDaoUtils.getRfidListDataByRfid(rfid),ant);
//            rfidListBean.addBean(rfidListBean.checkRfidList,rfid);
            haveNewRfidBean ++;
        }
    }


    public static class EventCheck{
        RfidListBean listBean;
        public EventCheck(RfidListBean listBean) {
            this.listBean = listBean;
        }
    }

    @Subscribe
    public void onCheckEvent(EventCheck event){
        if(isFinishing())return;
        rfidListBean = event.listBean;
        setRfidRecycle();
        text_xls.setText("盘点数量："+rfidListBean.getBookRfidList().size());
    }

    private final int REQUEST_READ_FILE_CHOOSE = 41;
    String resultPath = null;
    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        LogUtil.i("onActivityResult---requestCode>"+requestCode);
        if (resultCode == Activity.RESULT_OK) {//是否选择，没选择就不会继续
//            Uri uri = data.getData();//得到uri，后面就是将uri转化成file的过程。
//            String path = FileUtils.getPathFromUri(mContext,uri);

            List<String> list = data.getStringArrayListExtra(Constant.RESULT_INFO);
            if(list == null || list.size() == 0){

            }else {
                resultPath = list.get(0);
            }
            LogUtil.i("path-getPathFromUri-->"+resultPath);
            if(TextUtils.isEmpty(resultPath)){
                DialogUtils.DialogOkMsg(mContext,"读取文档失败");
                return;
            }
            showLoading("导入中...请稍等!");

            Observable.create(new ObservableOnSubscribe<Integer>() {
                // 1\. 创建被观察者 & 生产事件
                @Override
                public void subscribe(ObservableEmitter<Integer> emitter) throws Exception {
                    ArrayList<RfidListData> rfidListData = ExcelUtil.parseFromExcel(resultPath);

                    if(rfidListData == null || rfidListData.size()<1){
                        emitter.onNext(0);
                    }else {
                        GreenDaoUtils.rfidListDataInsertData(rfidListData, new GreenDaoUtils.GreenDaoInserCallBack() {
                            @Override
                            public void onDataInsert(int count) {
                                if(count != 1){
                                    emitter.onNext(0);
                                }else {
                                    emitter.onNext(rfidListData.size());
                                }
                            }
                        });
                    }
                    emitter.onComplete();
                }
            })   .subscribeOn(Schedulers.io())
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribe(new Observer<Integer>() {
                        // 2\. 通过通过订阅（subscribe）连接观察者和被观察者
                        // 3\. 创建观察者 & 定义响应事件的行为
                        @Override
                        public void onSubscribe(Disposable d) {

                        }
                        // 默认最先调用复写的 onSubscribe（）

                        @Override
                        public void onNext(Integer size) {
                            dismissProgress();
                            switch (size){
                                case 0:
                                    DialogUtils.showErrorDialog(mContext,"提示","导入失败");
                                    break;
                                case 1:
                                    DialogUtils.showSuccessrDialog(mContext,"提示","导入成功");
                                    break;
                            }

                            text_xls.setText("盘点数："+size);
                        }

                        @Override
                        public void onError(Throwable e) {

                        }

                        @Override
                        public void onComplete() {

                        }
                    });
        }
    }


    @Override
    protected void onDestroy() {
        // TODO Auto-generated method stub
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }


}


